<?php
/**
 * @author spenceryg
 * @date 2023/4/9
 * @time 12:03 上午
 * @focus love & life
 */


namespace app\api\controller;

use app\api1\controller\PayCommon;
use app\auto\model\Method;
use app\common\model\NewOrders;
use app\common\model\Orders;
use GuzzleHttp\Client;
use hg\apidoc\annotation as Apidoc;

use app\BaseController;
use app\common\model\MemberPointsLog;
use app\common\model\Order;
use app\common\model\PointProducts;
use hg\apidoc\utils\Cache;
use Yansongda\Pay\Exception\ContainerException;
use Yansongda\Pay\Pay;
use EasyWeChat\Factory;

/**
 * Class PointPay
 * @package app\api\controller
 * @Apidoc\Title("支付管理")
 * @Apidoc\Group("api")
 */
class PointPay extends BaseController
{

    /**
     * checkTerrace
     * @return mixed
     */
    public function checkTerrace()
    {
        $pay_type = $this->getPayType(); //该方法使用来判断用户扫码终端的
        $data = input();
        if ($pay_type === 'alipay') { //如果用户是通过支付宝扫码，进行支付宝相关操作
            $this->aliPay($data);
        } elseif ($pay_type === 'wechat') { //如果用户是通过微信扫码，进行微信相关操作
            $this->wePay($data);
        } elseif ($pay_type === false) {
            $this->wePay($data);
            echo "请使用支付宝或微信进行扫码";
            exit;
        }
    }

    /**
     * 判断扫码终端
     *
     * @return string|boolean
     */
    private function getPayType()
    {
        if (strstr($_SERVER['HTTP_USER_AGENT'], 'AlipayClient')) {
            return "alipay";
        } elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
            return "wechat";
        } else {
            return false;
        }
    }


    private function aliPay($param)
    {
        try {
            $product = PointProducts::find($param['id']);
            $subject = 'aidog充值购买' . ($product['integral'] + $product['reward_points']) . '积分';
            if ($product['is_integral']) {
                $subject = 'aidog充值购买' . $product['name'];
            }
            return Pay::alipay(config('alipay_payment'))->wap([
                'out_trade_no' => $param['member_id'] . '_' . $param['id'] . '_' . time(),
                'total_amount' => $product['money'],
                'subject' => $subject,
            ])->send();
        } catch (\Exception $e) {
            dump($e);
            exit;
        }

    }

    /**
     * alipay_notify_url
     * @return \Symfony\Component\HttpFoundation\Response
     * @Apidoc\Title("支付宝支付回调")
     */
    public function alipay_notify_url(): \Symfony\Component\HttpFoundation\Response
    {
        $alipay = Pay::alipay(config('alipay_payment'));
        try {
            $result = $alipay->verify();
            $result = $result->toArray();
            $out_trade_no = $result['out_trade_no'];
            $arr = explode('_', $out_trade_no);

            switch ($arr[0]) {
                case 'robot':
                    PayCommon::completeRobotOrder($arr[1],'支付宝',$result);
                    break;
                default:
                    $member_id = $arr[0];
                    $product_id = $arr[1];

                    $product = PointProducts::find($product_id);


                    $order_data = [
                        'member_id' => $member_id,
                        'point_products_id' => $product_id,
                        'trade_no' => $result['trade_no'],
                        'total_amount' => $result['total_amount'],
                        'integral' => $product['integral'] + $product['reward_points'],
                        'payment_method' => '支付宝',
                        'details' => json_encode($result),

                    ];
                    $order = Orders::create($order_data);
                    $order_id = $order->id;

                    $new_order_data = [
                        'name' => $product['name'],
                        'member_id' => $member_id,
                        'payment_method' => '支付宝',
                        'payment_time' => time(),
                        'purchase_type' => 'new',
                        'total_amount' => $result['total_amount'],
                        'payment_amount' => $result['total_amount'],
                        'payment_details' => $result,
                        'product_parameters' => $product,
                        'is_payment' => 1,
                        'order_number' => $result['trade_no'],
                        'is_apply_for_invoice' => 0,
                        'product_type' => $product['is_integral']?'point':'chatdog',
                    ];
                    $new_order = NewOrders::create($new_order_data);

                    // 积分和聊天会员 2种产品区别处理
                    if ($product['is_integral']) {
                        $member = \app\common\model\Member::find($member_id);
                        $chat_expiration_time = $member->chat_end_time;
                        $add_days = $product['integral'];
                        $add_time = $add_days * (60 * 60 * 24);

                        if ($chat_expiration_time < time()) {
                            // 如果会员日期小于time() 当前日期+
                            $end_time = time() + $add_time;
                        } else {
                            // 如果会员日期大于time() 会员日期加
                            $end_time = $chat_expiration_time + $add_time;
                        }

                        //  记录推荐者聊天会员时长
                        \app\common\model\ChatVipRecords::create([
                            'name' => '充值chatdog会员',
                            'days' => $add_days,
                            'money' => $result['total_amount'],
                            'end_time' => date('Y-m-d h:i:s', $end_time),
                            'member_id' => $member->id,
                            'source_id' => $order_id,
                        ]);

                        $member->chat_end_time = date('Y-m-d h:i:s', $end_time);
                        $member->save();

                    } else {
                        $member = \app\common\model\Member::find($member_id);
                        $member->point_num = $member->point_num + $product['integral'] + $product['reward_points'];
                        $member->save();

                        MemberPointsLog::create([
                            'member_id' => $member_id,
                            'num' => $product->integral + $product['reward_points'],
                            'end_num' => $member->point_num,
                            'remarks' => "积分充值",
                            'orders_id' => $order_id,
                        ]);
                    }

                    // 如何会员有推荐者上级 进行返佣金
                    $member = \app\common\model\Member::find($member_id);
                    if ($member['promoter_id']) {
                        $rate = config('pull_new_gifts.recharge_rebate') * 0.01;
                        $promoter_money = $result['total_amount'] * $rate;
                        \app\common\model\MemberBenefits::create([
                            'member_id' => $member['promoter_id'],
                            'name' => '推荐充值返佣金',
                            'money' => $promoter_money,
                            'subordinate_id' => $member_id,
                            'state' => 0,
                            'orders_id' => $order_id
                        ]);
                    }
                    break;
            }




        } catch (\Exception $e) {
            cache('order', $e);
        }
        return $alipay->success()->send(); // laravel 框架直接 return $alipay->success();
    }


    /**
     *
     * wepay_notify_url
     * @return \Symfony\Component\HttpFoundation\Response
     * @Apidoc\Title("微信支付回调")
     */
    public function wepay_notify_url(): \Symfony\Component\HttpFoundation\Response
    {
        $wepay = Pay::wechat(config('wechat_payment'));
        try {
            $result = $wepay->verify();
            $result = $result->toArray();
            $out_trade_no = $result['out_trade_no'];
            $arr = explode('_', $out_trade_no);
            $member_id = $arr[0];
            $product_id = $arr[1];

            $product = PointProducts::find($product_id);


            $order_data = [
                'member_id' => $member_id,
                'point_products_id' => $product_id,
                'trade_no' => $result['transaction_id'],
                'total_amount' => $result['total_fee'] / 100,
                'integral' => $product['integral'] + $product['reward_points'],
                'payment_method' => '微信',
                'details' => json_encode($result),

            ];

            $order = Orders::create($order_data);
            $order_id = $order->id;

            $new_order_data = [
                'name' => $product['name'],
                'member_id' => $member_id,
                'payment_method' => '微信',
                'payment_time' => time(),
                'purchase_type' => 'new',
                'total_amount' => $result['total_fee'] / 100,
                'payment_amount' => $result['total_fee'] / 100,
                'payment_details' => $result,
                'product_parameters' => $product,
                'is_payment' => 1,
                'order_number' => $result['transaction_id'],
                'is_apply_for_invoice' => 0,
                'product_type' => $product['is_integral']?'point':'chatdog',
            ];
            $new_order = NewOrders::create($new_order_data);

            // 积分和聊天会员 2种产品区别处理
            if ($product['is_integral']) {
                $member = \app\common\model\Member::find($member_id);
                $chat_expiration_time = $member->chat_end_time;
                $add_days = $product['integral'];
                $add_time = $add_days * (60 * 60 * 24);

                if ($chat_expiration_time < time()) {
                    // 如果会员日期小于time() 当前日期+
                    $end_time = time() + $add_time;
                } else {
                    // 如果会员日期大于time() 会员日期加
                    $end_time = $chat_expiration_time + $add_time;
                }

                //  记录推荐者聊天会员时长
                \app\common\model\ChatVipRecords::create([
                    'name' => '充值chatdog会员',
                    'days' => $add_days,
                    'money' => $result['total_fee'] / 100,
                    'end_time' => date('Y-m-d h:i:s', $end_time),
                    'member_id' => $member->id,
                    'source_id' => $order_id,
                ]);

                $member->chat_end_time = date('Y-m-d h:i:s', $end_time);
                $member->save();

            } else {
                $member = \app\common\model\Member::find($member_id);
                $member->point_num = $member->point_num + $product['integral'] + $product['reward_points'];
                $member->save();

                MemberPointsLog::create([
                    'member_id' => $member_id,
                    'num' => $product->integral + $product['reward_points'],
                    'end_num' => $member->point_num,
                    'remarks' => "积分充值",
                    'orders_id' => $order_id,
                ]);
            }

            // 如何会员有推荐者上级 进行返佣金
            $member = \app\common\model\Member::find($member_id);
            if ($member['promoter_id']) {
                $rate = config('pull_new_gifts.recharge_rebate') * 0.01;
                $promoter_money = $result['total_fee'] / 100 * $rate;
                \app\common\model\MemberBenefits::create([
                    'member_id' => $member['promoter_id'],
                    'name' => '推荐充值返佣金',
                    'money' => $promoter_money,
                    'subordinate_id' => $member_id,
                    'state' => 0,
                    'orders_id' => $order_id
                ]);
            }

        } catch (\Exception $e) {
            cache('order', $e);
        }
        return $wepay->success()->send(); // laravel 框架直接 return $alipay->success();
    }


    private function wePay($param)
    {

        $config = [
            'app_id' => config('front_end.app_id'),
            'secret' => config('front_end.secret'),
            'response_type' => 'array',
        ];

        $app = Factory::miniProgram($config);
        $access_token = $app->access_token->getToken()['access_token'];
        $client = new Client();
        $res = $client->post("https://api.weixin.qq.com/wxa/generatescheme?access_token=" . $access_token, [
            'json' => [
                'jump_wxa' => [
                    'query' => 'id=' . $param['id'] . '&uid=' .  $param['member_id'],
                    'path' => 'pages/wepay/wepay'
                ]
            ]
        ]);


        $res = $res->getBody()->getContents();
        // 重定向, 使用header跳转
        $res = json_decode($res, true);  // 转数组  方便取值
        $url = $res['openlink'];
        header("Location:" . $url);
        exit;

    }


    public function successPage()
    {
        return '支付成功';
    }


}
